#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QMessageBox>
#include <QTime>
#include <QDebug>
#include <QGraphicsOpacityEffect>
//#include <QMediaPlayList>

//#include <mpegfile.h>
//#include <id3v2.h>
//#include <id3v2tag.h>
//#include <attachedpictureframe.h>
//#include <fileref.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QString currentPath=QDir::currentPath();
    QFileInfo fileInfo(currentPath);
    url=fileInfo.absoluteFilePath();

//    TagLib::MPEG::File f(TagLib::FileName(L"C:/Users/Tyz/Desktop/homework/MyMusic/MyMusic/music/富士山下-陈奕迅.mp3"));
//    TagLib::ID3v2::Tag *tag=f.ID3v2Tag(true);
//    TagLib::ID3v2::FrameList frameList=tag->frameList("APIC");
//    if(frameList.isEmpty())
//    {
//        return;
//    }
//    TagLib::ID3v2::AttachedPictureFrame *coverImg=static_cast<TagLib::ID3v2::AttachedPictureFrame *>(frameList.front());
//    QPixmap map;
//    map.loadFromData((const uchar *) coverImg->picture().data(),coverImg->picture().size());
//    ui->imagBack->setPixmap(map.scaled(ui->imagBack->width(),ui->imagBack->height(),Qt::KeepAspectRatio));
//    stowFlag=MainWindow::stowStatus::noStow;
    m_player=new QMediaPlayer(this,QMediaPlayer::LowLatency);
    m_playerList=new QMediaPlaylist(this);
    m_player->setVolume(10);
    m_playerList->setPlaybackMode(QMediaPlaylist::Sequential);
    ui->listWidget->currentIndex();
    m_playerList->currentMedia();
    //获取媒体时长
    connect(m_player,&QMediaPlayer::durationChanged,this,[=](qint64 dura)
    {
       ui->currentMediaTime->setText(QString("%1::%2").arg(dura/1000/60,2,10,QChar('0')).arg(dura/1000-dura/1000/60*60));
       ui->progressSlider->setRange(0,dura);

    });

    //获取当前播放时长
    connect(m_player,&QMediaPlayer::positionChanged,this,[=](qint64 pos)
    {
        ui->currentPlayTime->setText(QString("%1::%2").arg(pos/1000/60,2,10,QChar('0')).arg(pos/1000-pos/1000/60*60,2,10,QChar('0')));
        ui->progressSlider->setValue(pos);
    });
    connect(ui->progressSlider,&QSlider::sliderMoved,m_player,&QMediaPlayer::setPosition);
    connect(ui->volumSlider,&QSlider::sliderMoved,m_player,&QMediaPlayer::setVolume);
    m_player->setPlaylist(m_playerList);
    ui->volumSlider->setRange(0,50);
    ui->progressSlider->setStyleSheet("QSlider::groove:horizontal{border:0px;height:4px;}"
                                "QSlider::sub-page:horizontal{background:red;}"
                                "QSlider::add-page:horizontal{background:lightgray;}"
                                "QSlider::handle:horizontal{background:black;width:10px;border-radius:5px;margin:-3px 0px -3px 0px;}");
    ui->volumSlider->setStyleSheet("QSlider::groove:horizontal{border:0px;height:4px;}"
                              "QSlider::sub-page:horizontal{background:brown;}"
                              "QSlider::add-page:horizontal{background:lightgray;}"
                              "QSlider::handle:horizontal{background:green;width:10px;border-radius:5px;margin:-3px 0px -3px 0px;}");
    const QString m_red_SheetStyle = "min-width: 30px; min-height: 40px;max-width:40px; max-height: 40px;border-radius: 8px;  border:1px solid black;background:white";
    ui->imagBack->setStyleSheet(m_red_SheetStyle);  //改成 红色圆形
}

MainWindow::~MainWindow()
{
    delete ui;
}

//有效性判断
void MainWindow::errorMessgBox()
{
    if(fileList.empty())
    {
       QMessageBox::information(this,"错误","没有文件",QMessageBox::Yes);
       return;
    }
}

void MainWindow::on_StartBtn_clicked()
{
    errorMessgBox();
    if(m_player->state()==QMediaPlayer::State::StoppedState)
    {
        //列表循环
        m_player->play();
        QPixmap pause=QPixmap(":/img/music_icon_pause.png");
        ui->StartBtn->setIcon(pause);
    }
    else if(m_player->state()==QMediaPlayer::PlayingState)
    {
        m_player->pause();
        QPixmap pause=QPixmap(":/img/music_icon_play.png");
        ui->StartBtn->setIcon(pause);
    }
    else if(m_player->state()==QMediaPlayer::PausedState)
    {
        m_player->play();
        QPixmap pause=QPixmap(":/img/music_icon_pause.png");
        ui->StartBtn->setIcon(pause);
    }
    return;
}


void MainWindow::on_PreBtn_clicked()
{
    //有效性判断
    int count=m_playerList->mediaCount();
    int currentPos=m_playerList->currentIndex();
//    如果当前的最后一首大于总数则从0开始
    if(currentPos==0)
    {
        currentPos=count-1;
        ui->listWidget->setCurrentRow(currentPos);
        m_playerList->previous();
        m_player->play();
    }
    else
    {
        currentPos-=1;
        ui->listWidget->setCurrentRow(currentPos);
        m_playerList->previous();
        m_player->play();
    }
    m_playerList->setCurrentIndex(currentPos);
    QPixmap pause=QPixmap(":/img/music_icon_pause.png");
    ui->StartBtn->setIcon(pause);
    m_player->play();
    return;
}

void MainWindow::on_Nextbtn_clicked()
{
    //有效性判断
    errorMessgBox();
    //获取总媒体个数
    int count=m_playerList->mediaCount();
//    获取到位置
    int currentPos=m_playerList->currentIndex();
    qDebug()<<currentPos;


    if(currentPos==count-1)
    {
        currentPos=0;
        ui->listWidget->setCurrentRow(0);
        m_player->play();
    }
    else
    {
        currentPos+=1;
        ui->listWidget->setCurrentRow(currentPos);
        m_playerList->next();
        m_player->play();
    }
    m_playerList->setCurrentIndex(currentPos);

    QPixmap pause=QPixmap(":/img/music_icon_pause.png");
    ui->StartBtn->setIcon(pause);
    return;
}


void MainWindow::on_volume_btn_clicked()
{
    if(m_player->isMuted()==true)
    {
        m_player->setMuted(false);
        QPixmap voice=QPixmap(":/img/music_icon_volume.png");
        ui->volume_btn->setIcon(voice);
    }
    else
    {
        m_player->setMuted(true);
        QPixmap muted=QPixmap(":/img/music_icon_mute.png");
        ui->volume_btn->setIcon(muted);
    }
}


void MainWindow::on_opneFile_clicked()
{
    QString filter="音频文件(*.mp3 *.wav)";
    fileList=QFileDialog::getOpenFileNames(this,"请选择音频文件",url,filter);
    for(int j=0;j<fileList.count();j++)
    {
        m_playerList->addMedia(QMediaContent(QUrl(fileList[j])));
    }
    for(int k=0;k<fileList.count();k++)
    {
        QFileInfo Fileinfor(fileList[k]);
        QString name=Fileinfor.fileName();
        QListWidgetItem *item = new QListWidgetItem(QIcon(":/img/MusicIcon.png"),name);
        //添加图标
        ui->listWidget->setSpacing(15);
        item->setTextAlignment(Qt::AlignRight);
        ui->listWidget->addItem(item);
    }
    ui->listWidget->setCurrentRow(0);
    m_playerList->setCurrentIndex(0);
}

void MainWindow::on_volumSlider_sliderMoved(int position)
{
   m_player->setVolume(position);
}

void MainWindow::on_volumSlider_valueChanged(int value)
{
    if(value==0)
    {
        m_player->setMuted(true);
        QPixmap muted=QPixmap(":/img/music_icon_mute.png");
        ui->volume_btn->setIcon(muted);
        m_player->setVolume(0);
        ui->volumeText->setText(QString("%1").arg(value));
    }
    else
    {
        m_player->setMuted(false);
        QPixmap muted=QPixmap(":/img/music_icon_volume.png");
        ui->volume_btn->setIcon(muted);
        m_player->setVolume(value);
        qDebug()<<value;
        ui->volumeText->setText(QString("%1").arg(value));
    }
}

void MainWindow::on_progressSlider_valueChanged(int value)
{
   ui->progressSlider->setValue(value);
}

void MainWindow::on_listWidget_doubleClicked(const QModelIndex &index)
{

    int currentPos = ui->listWidget->currentRow();
    m_playerList->setCurrentIndex(currentPos);
    m_player->play();
    QPixmap pause=QPixmap(":/img/music_icon_pause.png");
    ui->StartBtn->setIcon(pause);
}


void MainWindow::on_comboBox_activated(int index)
{
    switch (index)
    {
        case MainWindow::playModel::order:
            m_playerList->setPlaybackMode(QMediaPlaylist::Loop);
        case MainWindow::playModel::listing:
            m_playerList->setPlaybackMode(QMediaPlaylist::Sequential);
        case MainWindow::playModel::single:
            m_playerList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);;
        case MainWindow::playModel::random:
            m_playerList->setPlaybackMode(QMediaPlaylist::Random);
    }
}

void MainWindow::on_lineEdit_editingFinished()
{
//    获取文本
    QString content=ui->lineEdit->text();
    if(content==nullptr)
    {
        errorMessgBox();
        return;
    }
    for(int i=0;i<ui->listWidget->count();i++)
    {
        QListWidgetItem *item=ui->listWidget->item(i);
       if(item->text().contains(content,Qt::CaseInsensitive))
        {
            ui->listWidget->setCurrentRow(i);
            ui->listWidget->currentIndex();
            ui->listWidget->scrollToItem(item);
        }
    }
}


void MainWindow::on_Search_clicked()
{
    on_lineEdit_editingFinished();
}


void MainWindow::on_stowBtn_clicked()
{
    QString songName=ui->listWidget->currentItem()->text();
    bool findSong=false;
    if(findSong==false)
    {
        nameElements.push_back(songName);
        QPixmap pause=QPixmap(":/img/liked.png");
        ui->stowBtn->setIcon(pause);
    }
    for(int i=0;i<nameElements.count();i++)
    {
        for(int j=0;j<ui->listWidget->count();j++)
        {
            QPixmap pause=QPixmap(":/img/like.png");
            ui->stowBtn->setIcon(pause);
//            nameElements.remove();
        }
    }




//    preferSong=ui->listWidget->currentItem()->text();
//    QPixmap pause=QPixmap(":/img/liked.png");
//    ui->stowBtn->setIcon(pause);
//    for(int i=0;i<nameElements.count();i++)
//    {
//        for(int j=0;j<ui->listWidget->count();j++)
//        {
//            if(nameElements[i]==ui->listWidget->currentItem()->text())
//            {
//                QPixmap pause=QPixmap(":/img/liked.png");
//                ui->stowBtn->setIcon(pause);
//            }
//            else
//            {
//                QPixmap pause=QPixmap(":/img/like.png");
//                ui->stowBtn->setIcon(pause);
//            }
//        }
//    }
        //如果当前的最后一首大于总数则从0开


}





